/*
 * @Author: TT-hzy 
 * @Date: 2024-06-01 18:24:20
 * @LastEditors: TT-hzy 
 * @LastEditTime: 2024-06-01 18:24:21
 * @Description: 
 */
/*
 * @Author: TT-hzy 
 * @Date: 2024-01-23 09:32:40
 * @LastEditors: TT-hzy 
 * @LastEditTime: 2024-01-23 15:08:29
 * @Description: 
 */

import 'dart:math';

import 'package:flutter/material.dart';

class WaterRipple extends StatefulWidget {
  final int count;
  final Color color;
  final Widget? child;
  final Size size;
  final PaintingStyle paintingStyle;
  const WaterRipple({
    super.key,
    this.count = 3,
    this.size = Size.zero,
    this.child,
    this.color = Colors.transparent,
    this.paintingStyle = PaintingStyle.fill,
  });

  @override
  createState() => _WaterRippleState();
}

class _WaterRippleState extends State<WaterRipple>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(
        milliseconds: 2000,
      ),
    );

    _controller.repeat();
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return CustomPaint(
          size: widget.size,
          painter: WaterRipplePainter(
            _controller.value,
            count: widget.count,
            color: widget.color,
            paintingStyle: widget.paintingStyle,
          ),
          child: widget.child,
        );
      },
    );
  }
}

class WaterRipplePainter extends CustomPainter {
  final double progress;
  final int count;
  final Color color;
  final PaintingStyle paintingStyle;

  final Paint _paint = Paint();

  WaterRipplePainter(
    this.progress, {
    this.count = 3,
    this.color = Colors.transparent,
    this.paintingStyle = PaintingStyle.fill,
  });

  @override
  void paint(Canvas canvas, Size size) {
    double radius = min(size.width / 2, size.height / 2);
    _paint.style = paintingStyle;
    for (int i = count; i >= 0; i--) {
      final double opacity = (1.0 - ((i + progress) / (count + 1)));
      Color opacityColor = color.withOpacity(opacity);
      _paint.color = opacityColor;

      double radius0 = radius * ((i + progress) / (count + 1));

      canvas.drawCircle(
        Offset(size.width / 2, size.height / 2),
        radius0,
        _paint,
      );
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}
